<template>
	<view class="booking-select">
		<!-- 预约到店模块 -->
		<view class="booking-module store-module">
			<view class="module-header">
				<text class="title">预约到店</text>
				<view class="location-bar">
					<image class="location-icon" src="/static/icons/location.png"></image>
					<text class="location-text">{{ locationText }}</text>
				</view>
			</view>
			<map 
				class="map"
				:latitude="centerLocation.latitude"
				:longitude="centerLocation.longitude"
				:markers="allStoreMarkers"
				:show-location="true"
				:enable-overlooking="false"
				:enable-rotate="false"
				:enable-3D="false"
				:scale="12"
			></map>
			<button class="book-btn" @tap="goToStoreBooking">
				<view class="btn-content">
					<view class="left-content">
						<text class="btn-text">预约到店</text>
						<text class="btn-desc">专业环境·舒适体验</text>
					</view>
					<text class="btn-icon">></text>
				</view>
			</button>
		</view>
		
		<!-- 上门服务模块 -->
		<view class="booking-module home-module">
			<view class="module-header">
				<text class="title">上门服务</text>
			</view>
			<map 
				class="map"
				:latitude="centerLocation.latitude"
				:longitude="centerLocation.longitude"
				:markers="allTechMarkers"
				:show-location="true"
				:enable-overlooking="false"
				:enable-rotate="false"
				:enable-3D="false"
				:scale="12"
			></map>
			<button class="book-btn" @tap="goToHomeMassage">
				<view class="btn-content">
					<view class="left-content">
						<text class="btn-text">上门服务</text>
						<text class="btn-desc">专业技师·贴心服务</text>
					</view>
					<text class="btn-icon">></text>
				</view>
			</button>
		</view>
	</view>
</template>

<script>
export default {
	computed: {
		// 计算所有门店标记（包括用户位置）
		allStoreMarkers() {
			return [this.userMarker].concat(this.storeMarkers)
		},
		// 计算所有技师标记（包括用户位置）
		allTechMarkers() {
			return [this.userMarker].concat(this.techMarkers)
		}
	},
	data() {
		return {
			centerLocation: {
				latitude: 39.909,
				longitude: 116.397
			},
			locationText: '定位中...',
			isLocating: false,  // 是否正在定位
			userMarker: {
				id: 0,
				latitude: 39.909,
				longitude: 116.397,
				iconPath: '/static/icons/location.png',
				width: 28,
				height: 28,
				anchor: { x: 0.5, y: 0.5 },
				callout: {
					content: '您的位置',
					color: '#333333',
					fontSize: 14,
					borderRadius: 4,
					padding: 6,
					display: 'ALWAYS',
					textAlign: 'center',
					bgColor: '#FFFFFF',
					boxShadow: '0 2px 4px rgba(0,0,0,0.1)'
				}
			},
			storeMarkers: [
				{
					id: 1,
					latitude: 39.915,
					longitude: 116.404,
					iconPath: '/static/icons/store-marker.png',
					width: 36,
					height: 36
				},
				{
					id: 2,
					latitude: 39.911,
					longitude: 116.389,
					iconPath: '/static/icons/store-marker.png',
					width: 36,
					height: 36
				}
			],
			techMarkers: [
				{
					id: 1,
					latitude: 39.913,
					longitude: 116.402,
					iconPath: '/static/icons/location.png',
					width: 36,
					height: 36
				},
				{
					id: 2,
					latitude: 39.908,
					longitude: 116.393,
					iconPath: '/static/icons/location.png',
					width: 36,
					height: 36
				}
			],
			jWeixin: null,
			isIOS: false
		}
	},
	
	onLoad() {
		// iOS 首次进入自动刷新
		// this.isIOS = /iPhone|iPad|iPod/i.test(navigator.userAgent);
		// if (this.isIOS && !sessionStorage.getItem('iosRefreshed_bookingSelect')) {
		// 	sessionStorage.setItem('iosRefreshed_bookingSelect', 'true');
		// 	window.location.reload();
		// 	return;
		// }
		// 获取当前位置
		this.getCurrentLocation()
		// 获取门店和技师列表
		this.getStoreList()
		this.getTechnicianList()
		this.checkUserRealName()
		},
		onShow() {
			this.checkUserRealName()
		},
	methods: {
		// Check if user has set their real name
		checkUserRealName() {
				// Get userInfo from localStorage
				const userInfoStr = uni.getStorageSync('userInfo')
				if (userInfoStr) {
					try {
						let userInfo
						// Parse userInfo if it's a string
						if (typeof userInfoStr === 'string') {
							const parsed = JSON.parse(userInfoStr)
							// Check if it's login response format
							if (parsed.code === 200 && parsed.data) {
								userInfo = parsed.data
							} else {
								userInfo = parsed
							}
						} else {
							userInfo = userInfoStr
						}
						
						// Check if realName is empty
						if (!userInfo.realName||userInfo.realName=='') {
							// Show modal asking user to set real name
							uni.showModal({
								title: '提示',
								content: '请先在个人信息中填写真实姓名',
								confirmText: '去填写',
								showCancel: false,
								success: (res) => {
									if (res.confirm) {
										// Navigate to my-info page
										uni.navigateTo({
											url: '/pages/my-info/my-info'
										})
									}
								}
							})
						}
					} catch (e) {
						console.error('解析用户信息失败', e)
					}
				}
			},
		// 获取门店列表
		async getStoreList() {
			try {
				const res = await uni.request({
					url: `${uni.$config.baseUrl}/store/store/listALL`,
					method: 'GET'
				})
				
				if (res.statusCode === 200 && res.data.code === 200) {
					const stores = res.data.rows || []
					this.storeMarkers = stores.map((store, index) => ({
						id: index + 1,
						latitude: store.latitude,
						longitude: store.longitude,
						iconPath: '/static/icons/store-marker.png',
						width: 36,
						height: 36,
						callout: {
							content: store.storeName,
							color: '#333333',
							fontSize: 14,
							borderRadius: 4,
							padding: 6,
							display: 'ALWAYS',
							textAlign: 'center',
							bgColor: '#FFFFFF',
							boxShadow: '0 2px 4px rgba(0,0,0,0.1)'
						}
					}))
				}
			} catch (err) {
				console.error('获取门店列表失败:', err)
			}
		},
		
		// 获取技师列表
		async getTechnicianList() {
			try {
				const res = await uni.request({
					url: `${uni.$config.baseUrl}/technician/technician/listAll`,
					method: 'GET'
				})
				
				if (res.statusCode === 200 && res.data.code === 200) {
					const technicians = res.data.rows || []
					this.techMarkers = technicians.map((tech, index) => ({
						id: index + 1,
						latitude: tech.latitude,
						longitude: tech.longitude,
						iconPath: '/static/icons/location.png',
						width: 36,
						height: 36,
						callout: {
							content: tech.name,
							color: '#333333',
							fontSize: 14,
							borderRadius: 4,
							padding: 6,
							display: 'ALWAYS',
							textAlign: 'center',
							bgColor: '#FFFFFF',
							boxShadow: '0 2px 4px rgba(0,0,0,0.1)'
						}
					}))
				}
			} catch (err) {
				console.error('获取技师列表失败:', err)
			}
		},
		
		// 逆地址解析
		async reverseGeocoder(latitude, longitude) {
			try {
				const location = `${latitude},${longitude}`
				const res = await uni.request({
					url: `${uni.$config.baseUrl}/map/geocoder/v1/reverse`,
					method: 'GET',
					data: {
						location: location,
						key: 'GJZBZ-5ZV6G-ID2QK-Q6ODP-WNIPQ-HZFB4'
					}
				})
				
				if (res.data.code === 200) {
					const result = res.data.data
					if (result && result.address_component) {
						const city = result.address_component.city || ''
						const district = result.address_component.district || ''
						
						if (district) {
							this.locationText = `${result.address}`
						} else {
							this.locationText = city+district || '未知位置'
						}
					} else {
						this.locationText = '未知位置'
					}
				} else {
					this.locationText = '未知位置'
				}
			} catch (err) {
				console.error('逆地址解析失败:', err)
				this.locationText = '未知位置'
			}
		},
		
		// 获取当前位置
		async getCurrentLocation() {
			if (this.isLocating) return
			this.isLocating = true
			
			try {
				// 获取当前页面URL
				const currentUrl = window.location.href.split('#')[0]
				
				// 获取jssdk配置
				const configRes = await uni.request({
					url: `${uni.$config.baseUrl}/wx/jssdk/config`,
					method: 'GET',
					data: {
						url: currentUrl
					}
				})
				
				if (configRes.statusCode === 200 && configRes.data.code === 200) {
					const config = configRes.data.data
					
					// 加载jweixin-module
					this.jWeixin = require('jweixin-module')
					
					// 配置微信JSSDK
					this.jWeixin.config({
						debug: false,
						appId: config.appId,
						timestamp: config.timestamp,
						nonceStr: config.nonceStr,
						signature: config.signature,
						jsApiList: ['getLocation', 'openLocation']
					})
					
					// 使用微信JSSDK获取位置
					this.jWeixin.ready(() => {
						this.jWeixin.getLocation({
							type: 'gcj02',
							success: (res) => {
								console.log('微信定位成功:', res)
								
								// 更新中心点位置
								this.centerLocation = {
									latitude: res.latitude,
									longitude: res.longitude
								}
								
								// 更新用户位置标记
								this.userMarker.latitude = res.latitude
								this.userMarker.longitude = res.longitude
								
								// 逆地址解析获取位置文本
								this.reverseGeocoder(res.latitude, res.longitude)
								
								// 获取门店和技师列表
								this.getStoreList()
								this.getTechnicianList()
							},
							fail: () => {
								console.error('微信定位失败')
								this.locationText = '定位失败'
								// 如果微信定位失败，尝试使用IP定位
								this.getLocationByIP()
							}
						})
					})
					
					this.jWeixin.error((err) => {
						console.error('微信JSSDK配置失败:', err)
						// 如果微信JSSDK配置失败，尝试使用IP定位
						this.getLocationByIP()
					})
				} else {
					console.error('获取JSSDK配置失败')
					// 如果获取配置失败，尝试使用IP定位
					this.getLocationByIP()
				}
			} catch (error) {
				console.error('加载jweixin-module失败:', error)
				// 如果加载jweixin-module失败，尝试使用IP定位
				this.getLocationByIP()
			} finally {
				this.isLocating = false
			}
		},
		
		// 使用IP定位
		async getLocationByIP() {
			try {
				const res = await uni.request({
					url: `${uni.$config.baseUrl}/map/location/v1/ip`,
					method: 'GET',
					data: {
						key: 'GJZBZ-5ZV6G-ID2QK-Q6ODP-WNIPQ-HZFB4'
					}
				})
				
				if (res.data.code === 200) {
					const result = res.data.data
					
					// 更新中心点位置
					this.centerLocation = {
						latitude: result.location.lat,
						longitude: result.location.lng
					}
					
					// 更新用户位置标记
					this.userMarker.latitude = result.location.lat
					this.userMarker.longitude = result.location.lng
					
					// 逆地址解析获取位置文本
					await this.reverseGeocoder(result.location.lat, result.location.lng)
					
					// 获取门店和技师列表
					await Promise.all([
						this.getStoreList(),
						this.getTechnicianList()
					])
				} else {
					console.error('IP定位失败:', res.data)
					this.locationText = '定位失败'
				}
			} catch (err) {
				console.error('IP定位请求失败:', err)
				this.locationText = '定位失败'
			}
		},
		
		// 跳转到店预约
		goToStoreBooking() {
			uni.navigateTo({
				url: `/pages/store-booking/store-booking?latitude=${this.centerLocation.latitude}&longitude=${this.centerLocation.longitude}&address=${encodeURIComponent(this.locationText)}`
			})
		},
		
		// 跳转上门按摩
		goToHomeMassage() {
			uni.navigateTo({
				url: '/pages/home-massage/home-massage'
			})
		}
	}
}
</script>

<style lang="scss">
.booking-select {
	min-height: 100vh;
	height: 100vh;
	background: #F8F8F8;
	display: flex;
	flex-direction: column;
	padding: 20rpx;
	box-sizing: border-box;
	overflow: hidden;
	
	.booking-module {
		flex: 1;
		height: calc(50vh - 30rpx);
		background: #FFFFFF;
		border-radius: 24rpx;
		padding: 30rpx;
		display: flex;
		flex-direction: column;
		box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.05);
		overflow: hidden;
		
		.module-header {
			margin-bottom: 24rpx;
			display: flex;
			align-items: center;
			justify-content: space-between;
			
			.title {
				font-size: 40rpx;
				color: #333;
				font-weight: 600;
			}
			
			.location-bar {
				display: flex;
				align-items: center;
				padding-right: 10rpx;
				
				.location-icon {
					width: 32rpx;
					height: 32rpx;
					margin-right: 8rpx;
				}
				
				.location-text {
					font-size: 30rpx;
					color: #666;
				}
			}
		}
		
		.map {
			flex: 1;
			width: 100%;
			height: 400rpx;
			border-radius: 16rpx;
			margin-bottom: 20rpx;
			overflow: hidden;
		}
		
		.book-btn {
			width: 100%;
			height: 120rpx;
			border-radius: 50rpx;
			border: none;
			padding: 0 40rpx;
			transition: all 0.3s ease;
			
			.btn-content {
				height: 100%;
				display: flex;
				align-items: center;
				justify-content: space-between;
				
				.left-content {
					display: flex;
					flex-direction: column;
					align-items: flex-start;
					justify-content: center;
				}
				
				.btn-icon {
					font-size: 36rpx;
					color: rgba(255, 255, 255, 0.9);
					font-family: "宋体";
					font-weight: bold;
				}
			}
			
			.btn-text {
				font-size: 38rpx;
				font-weight: 600;
				color: #FFFFFF;
				margin-bottom: 12rpx;
				letter-spacing: 2rpx;
				line-height: 1;
			}
			
			.btn-desc {
				font-size: 26rpx;
				color: rgba(255, 255, 255, 0.9);
				letter-spacing: 1rpx;
				line-height: 1;
				display: block;
			}
			
			&:active {
				transform: scale(0.98);
				opacity: 0.9;
				
				.btn-icon {
					transform: translateX(-4rpx);
				}
			}
		}
	}
	
	.store-module {
		margin-bottom: 20rpx;
		
		.book-btn {
			background: linear-gradient(135deg, #2B87FF, #1976D2);
			box-shadow: 0 8rpx 16rpx rgba(43, 135, 255, 0.2);
			
			&:active {
				box-shadow: 0 4rpx 8rpx rgba(43, 135, 255, 0.1);
			}
		}
	}
	
	.home-module {
		.book-btn {
			background: linear-gradient(135deg, #FF9B6A, #FF6B6B);
			box-shadow: 0 8rpx 16rpx rgba(255, 107, 107, 0.2);
			
			&:active {
				box-shadow: 0 4rpx 8rpx rgba(255, 107, 107, 0.1);
			}
		}
	}
}
</style> 